package com.boc.news.beans.json;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;

public class JsonArray {
	private ArrayList converArray;
	public JsonArray (){
		converArray = new ArrayList();
	}
	
	public JsonArray(Collection collection){
		this.converArray = (collection == null) ?new ArrayList() :new ArrayList(collection);
	}

	public JsonArray(Object array) throws JsonException {
        this();
        if (array.getClass().isArray()) {
            int length = Array.getLength(array);
            for (int i = 0; i < length; i ++) {
                this.put(Array.get(array, i));
            }
        } else {
            throw new JsonException("JsonArray initial value should be a string or collection or array.");
        }
    }
	
	public String toString() {
        try {
            return '[' + join(",") + ']';
        } catch (Exception e) {
            return null;
        }
    }
	
	public String join(String separator) throws JsonException {
        int len = converArray.size();
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < len; i += 1) {
            if (i > 0) {
                sb.append(separator);
            }
            String str = JsonConversion.valueToString(this.converArray.get(i));
            sb.append(str);
        }
        return sb.toString();
    }
	
	public void put(Object value){
		this.converArray.add(value);
	}
	
}
